package com.ruoyi.project.app.aspect;

import com.ruoyi.project.app.aspect.handler.*;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;

@Component
@Aspect
public class FieldVerify {


    private List<Handler> paramChainHandler = new ArrayList<>();
    {
        paramChainHandler.add(new NotNullHandler());//null
        paramChainHandler.add(new NotEmptyHandler());//空值，“null”，“undefined”
        paramChainHandler.add(new CheckEmailHandler());//邮箱格式
        paramChainHandler.add(new CheckUserHandler());//用户是否存在检查
        paramChainHandler.add(new ReleaseHandler());//释放的handler，以后要再加节点应该加在此节点前
        paramChainHandler.add(new ValidParamHandler());//处理@ValidParam
    }


    @Before("execution(* com.ruoyi.project.app.controller.*.*(..))")
    public void fieldVerify(JoinPoint point) throws Exception {
        //获取参数对象
        Object[] args = point.getArgs();
        //获取方法参数
        MethodSignature signature = (MethodSignature) point.getSignature();
        Parameter[] parameters = signature.getMethod().getParameters();

        for (int i = 0; i < parameters.length; i++) {
            Parameter parameter = parameters[i];
            for(Handler handler:paramChainHandler){
                if(handler instanceof ValidParamHandler){
                    handler.handler(parameter,args);
                }else{
                    if(handler.handler(parameter,args[i])){
                        //ReleaseHandler释放掉整条链
                        break;
                    }
                }
            }
        }
    }

}
